<?php

namespace App\Http\Controllers;

use App\Services\EnvConfigService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;

class EnvConfigController extends Controller
{
    protected $envConfigService;

    public function __construct(EnvConfigService $envConfigService)
    {
        $this->middleware('auth.api');
        $this->envConfigService = $envConfigService;
    }

    /**
     * 获取所有环境变量（按分组）
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        try {
            $config = $this->envConfigService->getAllEnvGrouped();
            return $this->success($config, '获取成功');
        } catch (\Exception $e) {
            return $this->error('获取配置失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取所有环境变量（原始格式）
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function all()
    {
        try {
            $config = $this->envConfigService->readEnv();
            return $this->success($config, '获取成功');
        } catch (\Exception $e) {
            return $this->error('获取配置失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 更新环境变量
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'configs' => 'required|array',
            'configs.*.key' => 'required|string|max:255',
            'configs.*.value' => 'nullable|string',
        ], [
            'configs.required' => '配置项不能为空',
            'configs.array' => '配置项必须是数组',
            'configs.*.key.required' => '配置键不能为空',
            'configs.*.key.string' => '配置键必须是字符串',
            'configs.*.value.string' => '配置值必须是字符串',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        try {
            $configs = $request->input('configs', []);
            $updated = $this->envConfigService->batchUpdateEnv($configs);

            if ($updated) {
                // 清除配置缓存
                Artisan::call('config:clear');
                return $this->success(null, '配置更新成功，配置缓存已清除');
            } else {
                return $this->error('配置更新失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('配置更新失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 添加环境变量
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'key' => 'required|string|max:255',
            'value' => 'nullable|string',
        ], [
            'key.required' => '配置键不能为空',
            'key.string' => '配置键必须是字符串',
            'value.string' => '配置值必须是字符串',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        try {
            $key = $request->input('key');
            $value = $request->input('value', '');

            // 检查键是否已存在
            $env = $this->envConfigService->readEnv();
            if (isset($env[$key])) {
                return $this->error('配置键已存在', 400);
            }

            $updated = $this->envConfigService->updateEnv([$key => $value]);

            if ($updated) {
                // 清除配置缓存
                Artisan::call('config:clear');
                return $this->success(null, '配置添加成功，配置缓存已清除');
            } else {
                return $this->error('配置添加失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('配置添加失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除环境变量
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        // 支持从查询参数或请求体中获取 keys
        $keys = $request->input('keys', []);
        
        // 如果是从查询参数获取（逗号分隔的字符串）
        if (is_string($keys)) {
            $keys = explode(',', $keys);
        }
        
        // 如果是从路由参数获取
        if ($request->route('key')) {
            $keys = [$request->route('key')];
        }

        $validator = Validator::make(['keys' => $keys], [
            'keys' => 'required|array',
            'keys.*' => 'required|string|max:255',
        ], [
            'keys.required' => '配置键不能为空',
            'keys.array' => '配置键必须是数组',
            'keys.*.required' => '配置键不能为空',
            'keys.*.string' => '配置键必须是字符串',
        ]);

        if ($validator->fails()) {
            return $this->validationError($validator);
        }

        try {
            // 禁止删除关键配置
            $protectedKeys = ['APP_KEY', 'JWT_SECRET', 'DB_PASSWORD'];
            
            foreach ($keys as $key) {
                if (in_array($key, $protectedKeys)) {
                    return $this->error("无法删除受保护的配置项：{$key}", 400);
                }
            }

            $deleted = $this->envConfigService->deleteEnv($keys);

            if ($deleted) {
                // 清除配置缓存
                Artisan::call('config:clear');
                return $this->success(null, '配置删除成功，配置缓存已清除');
            } else {
                return $this->error('配置删除失败', 500);
            }
        } catch (\Exception $e) {
            return $this->error('配置删除失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 刷新配置缓存
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        try {
            // 清除配置缓存，让系统重新读取 .env 文件
            Artisan::call('config:clear');
            
            return $this->success(null, '配置缓存已清除，新配置已生效');
        } catch (\Exception $e) {
            return $this->error('刷新配置缓存失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 清除配置缓存
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearCache()
    {
        try {
            Artisan::call('config:clear');
            
            return $this->success(null, '配置缓存已清除');
        } catch (\Exception $e) {
            return $this->error('清除配置缓存失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 删除环境变量（POST 方式，用于兼容不支持 DELETE 请求体的情况）
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteEnv(Request $request)
    {
        return $this->destroy($request);
    }
}

